﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using DoubleH.Plugins;
using Table = FCNS.Data.Table;
using System.Data;
using System.ComponentModel;
using DoubleH.Utility;
using System.Windows.Controls.Primitives;
using System.Diagnostics;
using System.IO;
using DoubleH.Utility.Configuration;
using DoubleH.Utility.IO;
using FCNS.Data;

namespace DoubleH
{
    /// <summary>
    /// WorkArea.xaml 的交互逻辑
    /// </summary>
    public partial class WorkArea : Window
    {
        public WorkArea()
        {
            InitializeComponent();
        }

        Table.SysConfig sysConfig = null;
        public MenuItemBinding selectedMenu = null;

        PluginManager pluginManager = new PluginManager();
        public PluginManager PluginManager { get { return pluginManager; } }

        public Menu ITopMenu { get { return TopMenu; } }

        public Menu IBottomMenu { get { return bottomMenu; } }

        public void Init()
        {
            if (!NormalUtility.ShowLoginWindowSuccess())
            {
                Application.Current.Shutdown();
                return;
            }

            InitSysVar();
            InitUserVar();
            //InitHotKey();
            InitMenu();
            InitToolBar();
            InitTheRightTopButton();
            InitTreeView();
            InitDataGrid();
            InitAlert();
            InitCpuEvent();
            LoadInitUI();
            CheckDateIsChanged();
            this.Dispatcher.BeginInvoke(new Action(InitPlugin));
        }

        private void InitSysVar()
        {
            sysConfig = Table.SysConfig.SysConfigParams;
            Table.StoreS.GetDefault();
            this.Title = FCNS.Data.DbDefine.SystemName;

            this.Closed += (s, ee) =>
            {
                pluginManager.UnloadAllExtension();
                ConfigSerializer.SaveConfig(DoubleHConfig.UserConfig, Table.UserS.LoginUser.Id);
            };
        }

        private void InitUserVar()
        {
            if (!loginUser.Content.ToString().Contains(Table.UserS.LoginUser._LoginName))
            {
                dataGridObject.ItemsSource = null;//如果不这样，切换用户就会显示旧用户的资料
                treeViewLeftMenu.ItemsSource = null;
            }

            this.loginUser.Content = "【当前登录用户:" + Table.UserS.LoginUser._LoginName + "】";
        }

        //private void InitHotKey()
        //{
        //    this.KeyUp += (ss, ee) =>
        //    {
        //        switch (ee.Key)
        //        {
        //            case Key.F1:
        //                OpenHelp();
        //                break;
        //            case Key.F2:
        //                LoginOff();
        //                break;
        //            case Key.F9:
        //                OpenCalc();
        //                break;
        //            case Key.F10:
        //                string file = DbDefine.baseDir + "error.cvs";
        //                //Table.ErrorS.Export(file, null, null);
        //                if (MessageWindow.Show("", "是否打开文件?", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
        //                    System.Diagnostics.Process.Start(file);
        //                break;
        //            case Key.F11:
        //                if (File.Exists("Update.exe"))
        //                    System.Diagnostics.Process.Start("Update.exe");
        //                else
        //                    MessageWindow.Show("升级程序文件丢失");
        //                break;
        //            case Key.F12:
        //                if (File.Exists("POS.exe"))
        //                    System.Diagnostics.Process.Start("POS.exe");
        //                else
        //                    MessageWindow.Show("POS 程序文件丢失");
        //                break;
        //        }
        //    };
        //}

        private void InitPlugin()
        {
            DefaultPluginHost pluginDefaultHost = new DefaultPluginHost();
            pluginDefaultHost.Initialize(this);
            pluginManager.Initialize(pluginDefaultHost);
            pluginManager.LoadAllExtension();
        }

        private void InitTheRightTopButton()
        {
            expanderConfig.Header = Table.UserS.LoginUser._GroupSName;

            expanderConfig.Expanded += (ss, ee) => { expanderConfig.Cursor = Cursors.Hand; expanderConfig.Height = 110; };
            expanderConfig.MouseLeave += (ss, ee) => { expanderConfig.Cursor = Cursors.Arrow; expanderConfig.IsExpanded = false; expanderConfig.Height = 25; };
            buttonAppConfig.Click += (ss, ee) => pluginManager.LoadPlugin(DbDefine.baseDir + "SysConfig.dll",null,DataTableText.系统配置,null,null);

            buttonLogoff.Click += (ss, ee) => LoginOff();
            buttonHelp.Click += (ss, ee) => OpenHelp();
            buttonCalc.Click += (ss, ee) => OpenCalc();
        }

        private void InitAlert()
        {
            System.Windows.Forms.Timer t = new System.Windows.Forms.Timer();
            t.Interval = DoubleHConfig.UserConfig.AlertTime * 60000;
            t.Tick += (ss, ee) => GetMessageS();
            t.Start();
        }

        private void InitTreeView()
        {
            treeViewLeftMenu.MouseUp += (ss, ee) =>
            {
                if (treeViewLeftMenu.SelectedItems.Count == 0)
                    return;

                MenuItemBinding tb = treeViewLeftMenu.SelectedItems[0] as MenuItemBinding;
                if (tb == null)
                    return;
                if (tb != null && tb == selectedMenu)
                    return;

                //SaveDataGridColumnsWidthAndIndex();
                //clickSearch = false;
                if (tb.SubItems.Count != 0)//选中父类
                    //selectedMenu = tb.SubItems[0];
                    selectedMenu = tb.SubItems[0];
                else
                    selectedMenu = tb;

                TreeViewNodeClick();
            };
        }

        private void InitDataGrid()
        {
            dataGridObject.SizeChanged += (ss, ee) =>
                        {
                            Thickness tk = expanderMore.Margin;
                            expanderMore.Margin = new Thickness(treeViewLeftMenu.Width / 2 + this.Width / 2, tk.Top, tk.Right, tk.Bottom);
                        };


            dataGridObject.MouseDoubleClick += (ss, ee) =>
            {
                if (dataGridObject.SelectedItem == null)
                    return;

                switch (selectedMenu.TableText)
                {
                    case DataTableText.Pos机器号:
                        Table.PosS pos = dataGridObject.SelectedItem as Table.PosS;
                        switch (pos.Enable)
                        {
                            case Table.PosS.EnumEnable.启用:
                                if (MessageWindow.Show("", "确定要停用 " + pos.PosNO + "/" + pos.PosName + " 吗?", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                                    pos.ZuoFei();
                                break;
                            case Table.PosS.EnumEnable.评估:
                                if (MessageWindow.Show("", "确定要审核 " + pos.PosNO + "/" + pos.PosName + " 吗?", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                                    pos.ShenHe();
                                break;
                            case Table.PosS.EnumEnable.停用:
                                if (MessageWindow.Show("", "确定要启用 " + pos.PosNO + "/" + pos.PosName + " 吗?", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                                    pos.ShenHe();
                                break;
                        }
                        break;

                    default:
                        selectedMenu.DataTable = dataGridObject.SelectedItem as FCNS.Data.Table.DataTableS;
                        pluginManager.LoadPlugin(DbDefine.baseDir + selectedMenu.DllFile, null,selectedMenu.TableText,selectedMenu.DataTable,selectedMenu.Tag);
                        break;
                }
            };


            MenuItem obj1 = new MenuItem() { Header = "添加到POS禁售列表" };
            dataGridObject.ContextMenu.Items.Insert(0, obj1);
            obj1.Click += (ss, ee) =>
                {
                    if (dataGridObject.SelectedItem == null)
                        return;
                    try
                    {
                        Process.Start(DbDefine.baseDir + "POS.exe", "p " + ((Table.ProductS)dataGridObject.SelectedItem).Id.ToString());
                    }
                    catch
                    {
                        Table.ErrorS.WriteLogFile("POS.exe 文件丢失");
                    }
                };
            MenuItem obj2 = new MenuItem() { Header = "编辑收银员列表" };
            dataGridObject.ContextMenu.Items.Insert(0, obj2);
            obj2.Click += (ss, ee) =>
            {
                if (dataGridObject.SelectedItem == null)
                    return;
                try
                {
                    Process.Start(DbDefine.baseDir + "POS.exe", "u " + ((Table.PosS)dataGridObject.SelectedItem).PosNO);
                }
                catch
                {
                    Table.ErrorS.WriteLogFile("POS.exe 文件丢失");
                }
            };


            dataGridObject.ContextMenu.Opened += (ss, ee) =>
            {
                obj1.Visibility = (selectedMenu.TableText == DataTableText.可销售商品 || selectedMenu.TableText == DataTableText.物料清单) ? Visibility.Visible : Visibility.Collapsed;
                obj2.Visibility = selectedMenu.TableText == DataTableText.Pos机器号 ? Visibility.Visible : Visibility.Collapsed;
            };
        }

        private void InitToolBar()
        {
            buttonNew.Click += (ss, ee) =>
            {
                if (selectedMenu == null)
                    return;

                selectedMenu.DataTable = null;
                pluginManager.LoadPlugin(DbDefine.baseDir + selectedMenu.DllFile, null,selectedMenu.TableText,selectedMenu.DataTable,selectedMenu.Tag);
            };

            labelPre.MouseDown += (ss, ee) =>
            {
                if (int.Parse(labelIndex1.Content.ToString()) == 1)
                    return;

                uint start = uint.Parse(labelIndex1.Content.ToString()) - DoubleHConfig.UserConfig.GroupDataCount;
                labelIndex1.Content = start;
                labelIndex2.Content = (start - 1 + DoubleHConfig.UserConfig.GroupDataCount);
                BeginBindData();
            };

            labelNext.MouseDown += (ss, ee) =>
            {
                if (dataGridObject.Items.Count < DoubleHConfig.UserConfig.GroupDataCount)//如果列表已经没有项目就别搜索了
                    return;

                labelIndex1.Content = (int.Parse(labelIndex1.Content.ToString()) + DoubleHConfig.UserConfig.GroupDataCount);
                BeginBindData();
                labelIndex2.Content = (int.Parse(labelIndex2.Content.ToString()) + (dataGridObject.Items.Count < DoubleHConfig.UserConfig.GroupDataCount ? dataGridObject.Items.Count : (int)DoubleHConfig.UserConfig.GroupDataCount));
            };

            labelSearch.MouseLeftButtonUp += (ss, ee) =>
            {
                if (selectedMenu == null)
                    return;

                DoubleH.Utility.Search.WindowSearch so = new DoubleH.Utility.Search.WindowSearch();
                so.Init(selectedMenu);
                so.ShowDialog();
                if (so.Items!=null)
                    dataGridObject.ItemsSource = so.Items;
            };
            textBoxSearch.TextChanged += (ss, ee) =>
            {
                if (selectedMenu == null)
                    return;

                if (string.IsNullOrEmpty(textBoxSearch.Text))
                {
                    BeginBindData();
                    return;
                }

                StringBuilder sb = new StringBuilder();
                selectedMenu.DataGridColumn.Items.ForEach(f =>
                {
                    if (f.CanSearch)
                        sb.Append(f.BindingName + ",");
                });
                DoubleH.Utility.Search.SearchUtility su = new Utility.Search.SearchUtility();
                dataGridObject.ItemsSource = su.Search(dataGridObject.ItemsSource, sb.ToString().Split(','), textBoxSearch.Text);
            };

            expanderMore.Expanded += (ss, ee) => { expanderMore.Cursor = Cursors.Hand; expanderMore.Height = 196; };
            expanderMore.MouseLeave += (ss, ee) => { expanderMore.Cursor = Cursors.Arrow; expanderMore.IsExpanded = false; expanderMore.Height = 25; };
            //button_import.Click += (ss, ee) =>  EventImport(); 
            button_Export.Click += (ss, ee) => EventExport();
            button_delete.Click += (ss, ee) => EventDelete();
            button_ZuoFei.Click += (ss, ee) => EventZuoFei();
            button_print.Click += (ss, ee) => PrintFunction.Print(dataGridObject.SelectedItem, selectedMenu.TableText);
            button_printList.Click += (ss, ee) => PrintFunction.PrintList(dataGridObject, selectedMenu.TableText);
            button_refresh.Click += (ss, ee) => BeginBindData();
            button_edit.Click += (ss, ee) =>
            {
                selectedMenu.DataTable = dataGridObject.SelectedItem as FCNS.Data.Table.DataTableS;
                pluginManager.LoadPlugin(DbDefine.baseDir + selectedMenu.DllFile, null, selectedMenu.TableText, selectedMenu.DataTable, "Edit");
            };
        }

        /// <summary>
        /// 窗体加载后自动转到‘我的消息’界面和设置一些用户自己的配置
        /// </summary>
        private void LoadInitUI()
        {
            DataGridColumnBinding dgcb = DoubleHConfig.UserConfig.DataGridBinding.Find(f => f.TableText == DataTableText.待办事项);
            if (dgcb != null)
            {
                DataGridColumnHeaderBinding header = dgcb.Items.Find(f => f.BindingName.Contains("Flag"));
                if (header != null)
                {
                    header.BindingName = DoubleHConfig.UserConfig.ScheduleSUseImageForFlag ? "_Flag" : "Flag";
                    header.ColumnType = DoubleHConfig.UserConfig.ScheduleSUseImageForFlag ? "image" : "";
                }
            }//MenuItem mi = TopMenu.Items[0] as MenuItem;
            //var method = mi.GetType().GetMethod("add_Click");
            ////foreach (System.Reflection.MethodInfo mii in mi.GetType().GetMethods())
            ////{
            ////    if(mii.Name.Contains("Clic"))
            ////    MessageBox.Show(mii.Name);
            ////}
            //if (method != null)
            //{
            //    method.Invoke(mi, null);
            //    object obj= treeViewLeftMenu.FindName(DataTableText.我的消息.ToString());
            //    var method2 = obj.GetType().GetMethod("Click", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
            //    if (method2 != null)
            //        method2.Invoke(mi, null);
            //}
        }

        private void HyperlinkClick(object sender, RoutedEventArgs e)
        {
            Hyperlink obj = e.OriginalSource as Hyperlink;
            if (obj == null)
                return;

            if (obj.NavigateUri.ToString() == "点击查询")
                pluginManager.LoadPlugin(selectedMenu.DllFile, null, DataTableText.物流查询, dataGridObject.SelectedItem as FCNS.Data.Table.DataTableS, null);
            else
                pluginManager.LoadPlugin(selectedMenu.DllFile, null, DataTableText.物流跟踪, dataGridObject.SelectedItem as FCNS.Data.Table.DataTableS, null);
        }

        private void InitCpuEvent()
        {
            Table.CPU.InsertTableObject += new Table.CPU.TableObject(CPU_InsertTableObject);
            Table.CPU.ShenHeTableObject += new Table.CPU.TableObject(CPU_ShenHeTableObject);
            Table.CPU.ReloadTableList += new Table.CPU.TableObject(CPU_ReloadTableList);
        }

        ///// <summary>
        ///// 如果窗体关闭，记得要执行这个清理。因为数据库还没有关闭啊，那么CPU里面的事件就会重复罗。
        ///// </summary>
        //public void Clear()
        //{
        //    Table.CPU.ShenHeStoreSOrderS -= new Table.CPU.StoreOrderSShenHe(WuLiu);
        //}
    }
}